package com.example.springboot.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 功能：JWT拦截器
 * 作者：陈雷
 * 日期：2024/10/24 19:05
 */

public class Jwtinterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        String token = request.getHeader("token"); // 从header中获取token
//        if (StrUtil.isBlank(token)){
//            token = request.getParameter("token"); // 如果header中没有token，就从参数中获取
//        }
//        if (handler instanceof HandlerMethod){
//            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
//            if(annotation != null){
//                return true;
//            }
//        }
//        // 判断token是否为空
//        if (StrUtil.isBlank(token)){
//            throw new ServiceException("401","未登录");
//        }
//        String userId;
//        try {
//           userId = JWT.decode(token).getAudience().get(0); // 获取token中的userId解码
//        } catch (JWTDecodeException j) {
//            throw new ServiceException("401","请登录");
//        }
//        User user = userMapper.selectById(Integer.valueOf(userId));
//        if(user == null){
//            throw new ServiceException("401","用户不存在请登录");
//        }
//        //通过用户密码加密之后生成一个拦截器
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//        try {
//            jwtVerifier.verify(token); // 验证token
//        } catch (JWTDecodeException j) {
//            throw new ServiceException("401","请登录");
//        }
//        return true;
//    }


}